#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2020/5/6  16:18
# @Author: 余浪人
# @email: yulangren520@gmail.com
import requests, json,random
from db import r


def verify_pool_inland():
    '''
    国内代理验证
    :return:
    '''
    keys = r.hkeys('raw_pool_inland')
    for key in keys:
        k = key.decode('utf-8')
        val = json.loads(r.hget('raw_pool_inland', k))
        try:
            response = requests.get('http://icanhazip.com/', proxies={'http': k, 'https': k}, timeout=1)
            if val['ip'] == response.text.strip():
                r.hset('pool_inland', k, json.dumps(val))
            r.hdel('raw_pool_inland', k)
        except Exception as e:
            r.hdel('raw_pool_inland', k)
            print('验证超时',e)


def verify_pool_foreign():
    '''
    国外代理验证
    :return:
    '''
    keys = r.hkeys('raw_pool_foreign')
    for key in keys:
        k = key.decode('utf-8')
        val = json.loads(r.hget('raw_pool_foreign', k))
        try:
            response = requests.get('http://icanhazip.com/', proxies={'http': k, 'https': k}, timeout=1)
            if val['ip'] == response.text.strip():
                r.hset('pool_foreign', k, json.dumps(val))
            r.hdel('raw_pool_foreign', k)
        except Exception as e:
            r.hdel('raw_pool_foreign', k)
            print('验证超时',e)


def pool_inland():
    '''
    国内代理验证并返回
    :return:
    '''
    keys = r.hkeys('pool_inland')
    random.shuffle(keys)
    for key in keys:
        k = key.decode('utf-8')
        val = json.loads(r.hget('pool_inland', k))
        try:
            response = requests.get('http://icanhazip.com/', proxies={'http': k, 'https': k}, timeout=1)
            if val['ip'] == response.text.strip(): return val
        except Exception as e:
            pass
        r.hdel('pool_inland', k)


def pool_foreign():
    '''
    国外代理验证并返回
    :return:
    '''
    keys = r.hkeys('pool_foreign')
    random.shuffle(keys)
    for key in keys:
        k = key.decode('utf-8')
        val = json.loads(r.hget('pool_foreign', k))
        try:
            response = requests.get('http://icanhazip.com/', proxies={'http': k, 'https': k}, timeout=1)
            if val['ip'] == response.text.strip():return val
        except Exception as e:
            pass
        r.hdel('pool_foreign', k)
